<template>
    <div class="visualizationContainer">
      <div class="HeaderOfResultDisplay">
        <div class="RegionOfTreeIdUsed">
          <p class = "TreeName">决策模型名称：</p>
          <div class = "selectTreeName">
            <select id="test-dataset-select" v-model="selectedTree" @change="onTreeSetChange">
              <option v-for="item in tableData" :key="item.num" :value="item.id">
                {{ item.id }}
              </option>
            </select> 
          </div>
        </div>
      </div>
      <div class="charts-container">
        <div class="chart" style="width:100vw">
          <v-chart autoresize :option="pieChartOption" style="height: 400px"></v-chart>
        </div>
        <div class="chart">
          <v-chart :option="barChartOption" />
        </div>
      </div>

      <div class="footer-controls">
        <div class="dataset-select-container">
          <div class="RegionOfTestSet">
            <p>选择待诊断数据集：</p>
          </div>
          <select id="test-dataset-select" v-model="selectedTestDataSet" @change="onTestDataSetChange">
            <option v-for="item in testDataSetList" :key="item.id" :value="item.name">
              {{ item.name }}
            </option>
          </select>
        </div>

        <div class="return-button-container">
          <button @click="visualizeData" class="return-button">可视化</button>
        </div>
        
        <div class="return-button-container">
          <button @click="goBack" class="return-button">返回</button>
        </div>

      </div>
    </div>
  </template>
  
  <script>
  export default {
    name: 'DecisionTreeCharts',
    data() {
      return {
        treeIdofVisualization: '',
        dataIdofVisualization:'',
        selectedTestDataSet:'',
        selectedTree:'',
        testDataSetList:[],
        tableData:[],
        mappingList:[],
        chartData:{},
        pieChartOption: {},
        barChartOption: {},
      };
    },
    methods: {
      visualizeData(){
        this.fetchVisualizeData(this.treeIdofVisualization,this.dataIdofVisualization)
      },
      onTestDataSetChange() {
        const selectedItemInTestDataSetList = this.testDataSetList.find(item => item.name === this.selectedTestDataSet);
        let index = selectedItemInTestDataSetList.num
        this.dataIdofVisualization = this.mappingList[index-1].id
      },
      onTreeSetChange(){
        this.treeIdofVisualization = this.selectedTree
        console.log("this.treeIdofVisualization" + this.treeIdofVisualization)
      },
      async fetchFileList() {
        this.$axios.get('http://localhost/api/tree/treeList', {
          headers: {
            'token': sessionStorage.getItem('token')
            // token:"eyJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOiI3MDE3N2M5Yi1kNjVhLTQ0ZmUtODlkMS0wZDFlMzY1NmM0MDIiLCJleHAiOjE3MTIwMjkyMzd9.x7GvK27YZ_4FnJjrREjeFBo5e9MQesFzHAXzpn8uQuE"
          }
        })
        .then(response => {
          console.log(response.data);
          if (response.data.code == 200) {
            const fileList = response.data.data; // 获取数据数组
            this.tableData = fileList.map((file,index) => ({
              num:index+1,
              id: file.treeName, 
              dataSet: file.fileName,
            }));
            console.log(this.tableData); // 打印处理后的数据
          }
        })
        .catch(error => {
          console.error('获取决策模型列表失败', error);
          this.$message.error('获取决策模型列表失败:' + error);
        });
      },
      
      //获取文件列表
      async GetDataList() {
                this.$axios.get('http://localhost/api/tree/getTestDataList',{
                    headers: {        
                     'token': sessionStorage.getItem('token')
                    //  token:"eyJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOiI3MDE3N2M5Yi1kNjVhLTQ0ZmUtODlkMS0wZDFlMzY1NmM0MDIiLCJleHAiOjE3MTIwMjkyMzd9.x7GvK27YZ_4FnJjrREjeFBo5e9MQesFzHAXzpn8uQuE"
                    }
                    })
                    .then((response) => {
                    console.log(response.data);
                    if (response.data.code == 200) {
                        this.testDataSetList = response.data.data.map((item,index) => ({
                            num: index + 1,
                            name: item.name
                        }));
                        this.mappingList = response.data.data.map((item) => ({
                            id: item.id
                        }));
                        console.log(this.testDataSetList)
                    } else {
                        console.error('获取文件列表失败', response.data.msg);
                        this.$message.error('获取文件列表失败：' + response.data.msg);
                    }
                    })
                    .catch((error) => {
                    console.error('获取文件列表失败', error);
                    this.$message.error('获取文件列表失败');
                    });
            },
      goBack() {
        this.$router.push({
            path: '/TreeList',
            })
        },
        async fetchVisualizeData(treeName,dataId) {
          try {
            const response = await this.$axios.get(`http://localhost/api/tree/statisticAnalysis?treeName=${treeName}&dataId=${dataId}`, {
              headers: {
                'token': sessionStorage.getItem('token')
                // token:"eyJhbGciOiJIUzI1NiJ9.eyJVc2VySWQiOiI3MDE3N2M5Yi1kNjVhLTQ0ZmUtODlkMS0wZDFlMzY1NmM0MDIiLCJleHAiOjE3MTIwMjkyMzd9.x7GvK27YZ_4FnJjrREjeFBo5e9MQesFzHAXzpn8uQuE"
              },
            });
            if (response.data.code === 200) {
              this.chartData = response.data.data;
              this.generateCharts(this.chartData);
            } 
            else {
              console.error('获取数据失败：', response.data.msg);
            }
          } catch (error) {
            console.error('获取数据失败:', error);
          }
        },
      generateCharts(data) {
        // 从data中提取类别和值
        const categories = Object.keys(data);
        const values = Object.values(data).map(value => ({ value }));

        // 生成饼状图配置
        this.pieChartOption = {
            title: {
            left: 'center',
            },
            tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
            },
            legend: {
            orient: 'vertical',
            left: 'left',
            data: categories
            },
            series: [
            {
                name: '',
                type: 'pie',
                radius: '55%',
                center: ['50%', '60%'],
                data: categories.map((category, index) => ({
                value: values[index].value,
                name: category
                })),
                emphasis: {
                itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
                }
            }
            ]
        };

        // 生成柱状图配置
        this.barChartOption = {
            title: {
            left: 'center',
            },
            tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
            },
            grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
            },
            xAxis: [
            {
                type: 'category',
                show: true,
                interval: 0,
                axisLabel: {
                  interval: 'auto', // 自动调整间隔
                  formatter: function(params) {
                  var newParamsName = "";
                  var paramsNameNumber = params.length;
                  var provideNumber = 10; //一行显示几个字
                  var rowNumber = Math.ceil(paramsNameNumber / provideNumber);
                  if (paramsNameNumber > provideNumber) {
                    for (var p = 0; p < rowNumber; p++) {
                      var tempStr = "";
                      var start = p * provideNumber;
                      var end = start + provideNumber;
                      if (p == rowNumber - 1) {
                        tempStr = params.substring(start, paramsNameNumber);
                      } else {
                        tempStr = params.substring(start, end) + "\n";
                      }
                      newParamsName += tempStr;
                    }
                  } else {
                    newParamsName = params;
                  }
                  return newParamsName;
                } 
                },
                data: categories,
                axisTick: {
                alignWithLabel: true
                },
                
            }
            ],
            yAxis: [
            {
                type: 'value'
            }
            ],
            series: [
            {
                name: '数量',
                type: 'bar',
                barWidth: '60%',
                data: values
            }
            ]
        };
        }
    },

    mounted() {
      this.treeIdofVisualization = this.$route.query.decisionTreeIdToVisual;
      this.selectedTree = this.$route.query.decisionTreeIdToVisual;
      this.GetDataList();
      this.fetchFileList();
    },
  };
  </script>
  
  <style>
.visualizationContainer {
  display: flex;
  flex-direction: column;
  background-color: white; /* 更加柔和的背景色 */
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1); /* 添加阴影效果 */
  padding: 10px; /* 添加内边距 */
}
  
  .HeaderOfResultDisplay {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .RegionOfTreeIdUsed {
    min-width: 98%;
    min-height: 4%;
    background-color: #2980b9;
    color: white;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    font-weight: bold;
    display: flex; /* 应用flex布局 */
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
  }
  .TreeName {
  margin-right: 10px; /* 在文字和选择框之间添加一些间隔 */
}

.selectTreeName {
  display: inline-block; /* 使选择框与文字在同一行显示 */
}
  
  .charts-container {
    display: flex;
    justify-content: space-between;
  }
  
  .chart {
    flex: 1;
    border: 1px solid #ccc;
    border-radius: 8px;
    overflow: hidden;
    gap: auto;
  }
  .return-button-container {
    display: flex;
    justify-content: center; /* 按钮居中 */
    margin-top: 20px; /* 与上方内容保持一定间距 */
  }

  .return-button {
    background-color: #2980b9; /* 按钮背景颜色 */
    color: white; /* 按钮文字颜色 */
    border: none; /* 去掉边框 */
    padding: 10px 20px; /* 按钮内边距 */
    border-radius: 5px; /* 圆角边框 */
    cursor: pointer; /* 鼠标悬停时显示手形图标 */
    font-size: 16px; /* 文字大小 */
    transition: background-color 0.3s ease; /* 过渡动画 */
  }

  .return-button:hover {
    background-color: #21618C; /* 鼠标悬停时的背景颜色 */
  }

  .footer-controls {
  display: flex;
  justify-content: space-around; /* 修改此处以改进布局 */
  align-items: center;
  margin-top: 20px;
}

.dataset-select-container, .return-button-container {
  display: flex;
  align-items: center;
}

#test-dataset-select {
  max-height: 200px;
  overflow-y: auto; /* 如果选项超出最大高度，显示滚动条 */
  padding: 5px 10px; /* 添加内边距 */
  border: 1px solid #ccc; /* 轻微调整边框样式 */
  border-radius: 4px; /* 圆角边框 */
  background-color: white; /* 背景色 */
  color: #2980b9; /* 文字颜色 */
}

.RegionOfTestSet p {
  margin: 0;
  color: #2980b9; /* 字体颜色 */
  font-size: 16px; /* 调整字体大小 */
}

.return-button {
  background-color: #2980b9;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.return-button:hover {
  background-color: #21618C;
}
  </style>
